<template>
  <view class="chat-container">
    <!-- 聊天消息列表 -->
    <scroll-view class="chat-list" scroll-y :scroll-into-view="scrollToView">
      <!-- 聊天记录 -->
      <view v-for="(item, index) in chatHistory" :key="index" :id="'msg-'+index">
        <!-- 客服消息 -->
        <view v-if="item.type === 'service'" class="message service-message">
          <image class="avatar" src="/static/images/kefuLogo.png" mode="aspectFill"/>
          <view class="message-content">
            <rich-text :nodes="item.content"></rich-text>
          </view>
        </view>
        <!-- 用户消息 -->
        <view v-else class="message user-message">
          <view class="message-content">{{ item.content }}</view>
          <image class="avatar" src="/static/images/activities.png" mode="aspectFill"/>
        </view>
      </view>
    </scroll-view>

    <!-- 问题输入区域 -->
    <view class="input-area">
      <input 
        class="input-box"
        type="text"
        v-model="userInput"
        placeholder="请输入问题编号"
        @confirm="handleUserInput"
      />
      <button class="send-btn" @click="handleUserInput">发送</button>
    </view>
  </view>
</template>

<script>
import config from '@/config/config.js'

export default {
  data() {
    return {
      questionOptions: [],
      chatHistory: [],
      scrollToView: '',
      userInput: '',
      cacheKey: 'question_cache',
      cacheExpireKey: 'question_cache_expire'
    }
  },
  
  onLoad() {
    this.initChat()
  },
  
  methods: {
    // 初始化聊天
    async initChat() {
      await this.getQuestionList()
      
      // 发送欢迎消息
      this.addServiceMessage('您好，我是智能客服小森，很高兴为您服务。')
      
      // 延迟发送问题列表
      setTimeout(() => {
        let questionList = '您可以咨询以下问题：<br/>'
        this.questionOptions.forEach((item, index) => {
          questionList += `${index + 1}. ${item.question}<br/>`
        })
        questionList += '<br/>请输入问题编号进行咨询。'
        this.addServiceMessage(questionList)
      }, 500)
    },
    
    // 添加客服消息
    addServiceMessage(content) {
      this.chatHistory.push({
        type: 'service',
        content: content
      })
      this.scrollToBottom()
    },
    
    // 添加用户消息
    addUserMessage(content) {
      this.chatHistory.push({
        type: 'user',
        content: content
      })
      this.scrollToBottom()
    },
    
    // 处理用户输入
    handleUserInput() {
      if (!this.userInput) return
      
      const questionIndex = parseInt(this.userInput) - 1
      if (questionIndex >= 0 && questionIndex < this.questionOptions.length) {
        const question = this.questionOptions[questionIndex]
        
        // 添加用户问题
        this.addUserMessage(question.question)
        
        // 延迟显示答案
        setTimeout(() => {
          this.addServiceMessage(question.answer)
        }, 500)
      } else {
        // 输入的编号无效
        this.addUserMessage(this.userInput)
        setTimeout(() => {
          this.addServiceMessage('抱歉，我不明白您的问题。请输入有效的问题编号。')
        }, 500)
      }
      
      // 清空输入框
      this.userInput = ''
    },
    
    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        this.scrollToView = 'msg-' + (this.chatHistory.length - 1)
      })
    },
    
    // 获取问题列表
    async getQuestionList() {
      try {
        const cachedData = this.getCache()
        if (cachedData) {
          this.questionOptions = cachedData
          return
        }
        
        const res = await this.$http.post(config.api.customerService.queryQuestionList)
        
        if (res.data.code === 200) {
          this.questionOptions = res.data.data
          this.setCache(res.data.data)
        } else {
          throw new Error(res.data.message || '获取问题列表失败')
        }
      } catch (err) {
        console.error('获取问题列表失败:', err)
        uni.showToast({
          title: '获取问题列表失败',
          icon: 'none'
        })
      }
    },
    
    // 缓存方法保持不变
    getCache() {
      try {
        const expireTime = uni.getStorageSync(this.cacheExpireKey)
        if (expireTime && Date.now() < expireTime) {
          const cacheData = uni.getStorageSync(this.cacheKey)
          return cacheData || null
        }
        uni.removeStorageSync(this.cacheKey)
        uni.removeStorageSync(this.cacheExpireKey)
        return null
      } catch (err) {
        console.error('读取缓存失败:', err)
        return null
      }
    },
    
    setCache(data) {
      try {
        const expireTime = Date.now() + 24 * 60 * 60 * 1000
        uni.setStorageSync(this.cacheKey, data)
        uni.setStorageSync(this.cacheExpireKey, expireTime)
      } catch (err) {
        console.error('设置缓存失败:', err)
      }
    }
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.chat-list {
  flex: 1;
  padding: 20rpx;
  overflow-y: auto;
}

.message {
  margin-bottom: 30rpx;
  display: flex;
  align-items: flex-start;
}

.service-message {
  justify-content: flex-start;
}

.user-message {
  justify-content: flex-end;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin: 0 20rpx;
}

.message-content {
  max-width: 60%;
  padding: 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  line-height: 1.6;
  word-break: break-all;
}

.service-message .message-content {
  background-color: #fff;
  color: #333;
  margin-right: 100rpx;
}

.user-message .message-content {
  background-color: #000;
  color: #fff;
  margin-left: 100rpx;
}

.input-area {
  padding: 20rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
  display: flex;
  align-items: center;
}

.input-box {
  flex: 1;
  height: 72rpx;
  background-color: #f5f5f5;
  border-radius: 36rpx;
  padding: 0 30rpx;
  margin-right: 20rpx;
  font-size: 28rpx;
}

.send-btn {
  width: 120rpx;
  height: 72rpx;
  line-height: 72rpx;
  background-color: #000;
  color: #fff;
  border-radius: 36rpx;
  font-size: 28rpx;
  padding: 0;
}

/* 修复按钮边距问题 */
.send-btn::after {
  border: none;
}
</style>
